﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;

namespace comix
{
    public class BLogic
    {
        public static BoolResult IsUserNameavailable(string username)
        {
            BoolResult result = new BoolResult();
            SqlCommand com = new SqlCommand();
            com.CommandText = "SELECT COUNT(*) as result FROM USERS WHERE usr_username = @usr_username";
            com.Parameters.Add(new SqlParameter("@usr_username", username));
            object o = GetScalar(com, ref result.message);
            if (o != null)
                result.result = (Convert.ToInt32(o) == 0);
            return result;
        }

        public static UserResult RegisterUser(string username, string password, string deviceid, int resultflags, string firstname, string lastname, bool notifyok, bool newslettersok, string address, string city, string tk, string phone, int country)
        {
            UserResult ur = new UserResult();
            
            LCustomer c = new LCustomer();
            if (c.Register(username, password, deviceid, firstname, lastname, notifyok, newslettersok, address, city, tk, phone, country))
            {
                ur.usrid = c.Id;
                GetUserResults(resultflags, c, ref ur);
            }
            else
            {
                ur.usrid = 0;
                ur.message = c.LastError;
            }
            return ur;
        }

        private static void GetUserResults(int flag, LCustomer c, ref UserResult ur)
        {
            if ((flag & 2) == 2)
            {
                ur.usrcode = c.usercode;
            }
            if ((flag & 4) == 4)
            {
                ur.books = c.UserBooks;  
            }
        }





#region DBOperations

  

        private static object GetScalar(SqlCommand com, ref string message)
        {
            message = "OK";
            SqlConnection con = new SqlConnection();
            con.ConnectionString = WebConfigurationManager.ConnectionStrings["mainconectionstring"].ConnectionString;
            com.Connection = con;
            con.Open();
            object o = null;
            try
            {
                o = com.ExecuteScalar();
            }
            catch(Exception e)
            {
                message = e.Message;
            }
            con.Close();
            return o;
        }

      

#endregion
    }

    public class BoolResult
    {
        public bool result;
        public string message;
    }

    public class UserResult
    {
        public int usrid;
        public string usrcode;
        public string message;
        public UserBookCollection books;
    }
}